<template>
    <div class="comment-section">
  
      <!-- 评论输入框 -->
      <div class="comment-input-container">
        <div class="avatar">
          <el-avatar :size="32" :src="userAvatar" />
        </div>
        <div class="input-wrapper">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="说点什么吧"
            resize="none"
          />
          <div class="comment-tools">
            <div class="left-tools">
              <el-upload
                class="upload-attachment"
                action="#"
                :show-file-list="false"
                :before-upload="handleUploadAttachment"
              >
                <span class="attachment-link">
                  <el-icon><Plus /></el-icon>添加附件
                </span>
              </el-upload>
            </div>
            <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim()">
              发表评论
            </el-button>
          </div>
        </div>
      </div>
  
      <!-- 评论列表 -->
      <div class="comments-list">
        <div class="comments-header">
          <h4>全部评论 <span class="comment-count">({{ total }}条)</span></h4>
        </div>
        <div v-if="comments.length === 0" class="no-comments">
          <el-empty description="暂无评论" />
        </div>
        <div v-else class="comment-items">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="avatar">
              <el-avatar :size="32" :src="comment.userAvatar" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="username">{{ comment.username }}</span>
                <span class="time">{{ formatTime(comment.commentTime) }}</span>
              </div>
              <div class="comment-text" v-if="comment.replyTo">
                <span class="time">{{ formatTime(comment.commentTime) }}</span> 
                {{ comment.content }}
              </div>
              <div class="comment-text" v-else>
                {{ comment.content }}
              </div>
              <div v-if="comment.attachment" class="attachment">
                <el-link type="primary" :href="comment.attachment.url" target="_blank">
                  <el-icon><Document /></el-icon>
                  {{ comment.attachment.name }}
                </el-link>
              </div>
              <div class="comment-actions">
                <span class="action-item" @click="showReplyInput(comment.id)">回复</span>
                <span v-if="canDelete(comment)" class="action-item" @click="deleteComment(comment.id)">删除</span>
              </div>
  
              <!-- 回复输入框 -->
              <div v-if="activeReplyId === comment.id" class="reply-input-container">
                <div class="avatar">
                  <el-avatar :size="28" :src="userAvatar" />
                </div>
                <div class="reply-input-wrapper">
                  <el-input
                    v-model="replyContent"
                    type="textarea"
                    :rows="2"
                    placeholder="回复评论..."
                    resize="none"
                  />
                  <div class="reply-tools">
                    <el-button text @click="cancelReply">取消</el-button>
                    <el-button type="primary" @click="submitReply(comment.id)" :disabled="!replyContent.trim()">
                      回复
                    </el-button>
                  </div>
                </div>
              </div>
  
              <!-- 回复列表 -->
              <div v-if="comment.replies?.length" class="replies-list">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="avatar">
                    <el-avatar :size="28" :src="reply.userAvatar" />
                  </div>
                  <div class="reply-content">
                    <div class="reply-header">
                      <span class="username">{{ reply.username }}</span>
                      <span class="time">{{ formatTime(reply.commentTime) }}</span>
                    </div>
                    <div class="reply-text">{{ reply.content }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
  
        <!-- 分页 -->
      
        <div class="pagination">
          <div class="pagination-wrapper">
            <span class="total-text">共 {{ total }} 条</span>
            <el-select v-model="pageSize" class="page-size-select">
              <el-option :value="5" label="5条/页" />
              <el-option :value="10" label="10条/页" />
              <el-option :value="20" label="20条/页" />
            </el-select>
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              layout="prev, jumper, next"
              @current-change="handlePageChange"
            />
            <span class="page-text">页</span>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted,  } from 'vue'
  import { Document, Plus } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { ElMessageBox } from 'element-plus'
  import { getComments,submitComment as apiSubmitComment, submitReply as apiSubmitReply, deleteComment as apiDeleteComment } from '@/api/comment.js'

  // eslint-disable-next-line no-undef
  const workId = 4
// 测试时写死用户ID
const currentUserId = ref(1) // 这里暂时写死，实际应该从store获取
// 添加用户头像
const userAvatar = ref('../26.png') // 当前用户的头像URL
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}
  
  // 分页
  const currentPage = ref(1)
  const pageSize = ref(5)
  const total = ref(0)
  
  // 评论相关
  const commentContent = ref('')
  const comments = ref([])

  
  // 回复相关
  const activeReplyId = ref(null)
  const replyContent = ref('')
  

  // 修改提交评论的方法
const submitComment = async () => {
  if (!commentContent.value.trim()) return
  
  try {
    const params = {
      workId,
      userId: currentUserId.value,
      content: commentContent.value,
      superiorId: 0,  // 顶级评论的 superiorId 为 0
      respondentId: null  // 顶级评论没有回复对象
    }
    
    const res = await apiSubmitComment(params)
    if (res.code === 200) {
      await fetchComments()
      commentContent.value = ''
      ElMessage.success('评论发表成功')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('评论发表失败')
  }
}
  
  // 回复相关方法
  const showReplyInput = (commentId) => {
    activeReplyId.value = commentId
    replyContent.value = ''
  }
  
  const cancelReply = () => {
    activeReplyId.value = null
    replyContent.value = ''
  }
  
  // 提交回复的方法
const submitReply = async (commentId) => {
  if (!replyContent.value.trim()) return
  
  try {
    const parentComment = comments.value.find(c => c.id === commentId)
    const params = {
      workId,
      userId: currentUserId.value,
      content: replyContent.value,
      superiorId: commentId,  // 回复时的上级 ID 为被回复的评论 ID
      respondentId: parentComment?.userId  // 被回复人的用户 ID
    }
    
    const res = await apiSubmitReply(params)
    if (res.code === 200) {
      activeReplyId.value = null
      await fetchComments()
      replyContent.value = ''
      ElMessage.success('回复成功')
    }
  } catch (error) {
    console.error('提交回复失败:', error)
    ElMessage.error('回复失败')
  }
}

  // 删除评论方法
const deleteComment = async (commentId) => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm(
      '确定要删除这条评论吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 用户点击确定后继续删除操作
    const res = await apiDeleteComment(commentId)
    if (res.code === 200) {
      await fetchComments()
      ElMessage.success('删除成功')
    }
  } catch (error) {
    // 用户点击取消或发生错误
    if (error !== 'cancel') { // 不是用户主动取消
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}
  
  // 其他方法
  const handleUploadAttachment = (file) => {
    console.log('上传附件:', file)
    return false
  }
  
  
  // 修改获取评论列表的方法
const fetchComments = async () => {
  try {
    const res = await getComments({
      workId,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (res.code === 200) {
      // 确保每个评论都有头像，如果后端没有返回，使用默认头像
      comments.value = res.data.list.map(comment => ({
        ...comment,
        userAvatar: comment.userAvatar || '../26.png' // 添加默认头像
      }))
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  }
}
  
  const handlePageChange = (page) => {
    currentPage.value = page
    fetchComments()
  }
  
  const canDelete = (comment) => {
  // 使用 .value 访问计算属性的值
  return comment.userId === currentUserId.value
}
  
// 在组件挂载时获取当前用户头像
onMounted(async () => {
  await fetchComments()
})
  </script>
  
  <style scoped>
  .comment-section {
    background: #fff;
  }
  
  .tabs {
    display: flex;
    border-bottom: 1px solid #eee;
  }
  
  .tab-item {
    padding: 12px 24px;
    cursor: pointer;
    color: #666;
    position: relative;
  }
  
  .tab-item.active {
    color: #409EFF;
  }
  
  .tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background: #409EFF;
  }
  
  .comment-input-container {
    padding: 20px;
    display: flex;
    gap: 12px;
  }
  
  .input-wrapper {
    flex: 1;
  }
  
  .comment-tools {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
  }
  
  .attachment-link {
    color: #409EFF;
    cursor: pointer;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .comments-header {
    padding: 0 20px;
    margin-bottom: 16px;
  }
  
  .comment-count {
    color: #999;
    font-size: 14px;
    font-weight: normal;
  }
  
  .comment-item {
    padding: 16px 20px;
    display: flex;
    gap: 12px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .comment-content {
    flex: 1;
  }
  
  .comment-header {
    margin-bottom: 8px;
  }
  
  .username {
    font-weight: 500;
    margin-right: 8px;
  }
  
  .time {
    color: #999;
    font-size: 12px;
  }
  
  .comment-text {
    line-height: 1.6;
    margin-bottom: 8px;
  }
  
  .comment-actions {
    margin-top: 8px;
  }
  
  .action-item {
    color: #999;
    font-size: 12px;
    margin-right: 16px;
    cursor: pointer;
  }
  
  .action-item:hover {
    color: #409EFF;
  }
  
  .attachment {
    background: #f5f7fa;
    padding: 8px 12px;
    border-radius: 4px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }
  
  .reply-input-container {
    margin-top: 12px;
    display: flex;
    gap: 8px;
  }
  
  .reply-input-wrapper {
    flex: 1;
  }
  
  .reply-tools {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 8px;
  }
  
  .replies-list {
    margin-top: 12px;
    padding-left: 40px;
  }
  
  .reply-item {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
  }
  
  .reply-content {
    flex: 1;
  }
  
  .reply-header {
    margin-bottom: 4px;
  }
  
  .reply-text {
    font-size: 14px;
    line-height: 1.5;
  }
  
  .no-comments {
    padding: 40px 0;
    text-align: center;
  }
  
  /* 添加回复样式 */
.reply-to {
  color: #409EFF;
  margin-right: 4px;
}

.comment-text {
  line-height: 1.6;
  margin-bottom: 8px;
  word-break: break-all;
}
.pagination {
  padding: 20px;
  display: flex;
  align-items: center;
  /* 修改为居中对齐 */
  justify-content: center;
  gap: 10px;
  /* 添加容器宽度确保整体居中 */
  width: 100%;
}

/* 可以添加一个包装器来处理左对齐的总条数显示 */
.pagination-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}
.total-text {
  color: #606266;
  font-size: 14px;
}

.page-size-select {
  width: 100px;
}

.page-text {
  color: #606266;
  font-size: 14px;
}

/* 调整分页器样式 */
:deep(.el-pagination) {
  display: flex;
  align-items: center;
}

:deep(.el-pagination .el-input__inner) {
  text-align: center;
}
  </style>
  